﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using ToolUtil;
using zyconfig;
using zymarc;

namespace zymain
{
    public partial class FrmCgys : Form
    {
        public BindingSource BookData;
        public DataTable dt = new DataTable();
        public BindingSource CfData;
        private string mainKay;
        private int kjm;
        private int gjm;
        private string uid;
        private string marc = string.Empty;
        private bool flag = false;
        private string ydl;
        private string ydj;
        private string _mpc;
        private string ysTime = string.Empty, yeTime = string.Empty;
        private List<int> JfjmList = new List<int>();
        public int jfjm = 0;
        private List<int> GhsjmList = new List<int>();
        public int ghsjm = 0;

        public FrmCgys()
        {
            InitializeComponent();
        }
        private void AddJfKay()
        {
            using (DbOperHandler _open = new Common().Doh())
            {
                JfjmList.Clear();
                string sql = "select * from 采购经费库 where 支配人代码 like '% " + uid + " %' and 馆键码=" + this.gjm + " and 总额>实付 and 终止年代>= YEAR(GETDATE())  and 起始年代<= YEAR(GETDATE()) and 截止日期>=GETDATE() order by 序号 desc";
                _open.Reset();
                _open.SqlCmd = sql;
                DataTable dt = _open.GetDataTable();
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow dRow in dt.Rows)
                    {
                        this.jfKay.Items.Add(dRow["经费名称"].ToString().Trim());
                        this.JfjmList.Add(Convert.ToInt32(dRow["键码"].ToString().Trim()));
                    }
                    this.jfKay.SelectedIndex = 0;
                    this.jfjm = this.JfjmList[0];
                }
            }
        }

        private void AddGhsKay()
        {
            using (DbOperHandler _open = new Common().Doh())
            {
                GhsjmList.Clear();
                string sql = "select * from 发行商库 order by 键码 desc";
                _open.Reset();
                _open.SqlCmd = sql;
                DataTable dt = _open.GetDataTable();
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow dRow in dt.Rows)
                    {
                        this.fxsKay.Items.Add(dRow["发行商"].ToString().Trim());
                        this.GhsjmList.Add(Convert.ToInt32(dRow["键码"].ToString().Trim()));
                    }
                    this.fxsKay.SelectedIndex = 0;
                    this.ghsjm = this.GhsjmList[0];
                }
            }
        }
        private void FrmCgys_Load(object sender, EventArgs e)
        {
            string formName = "FrmTool";
            Form fr = System.Windows.Forms.Application.OpenForms[formName];
            if (fr != null)
            {
                FrmTool f1 = (FrmTool)fr;
                //取到Form1的值是1
                this.uid = f1.UserID;
                this.gjm = f1.Gjm;
            }
            this.AddJfKay();
            this.AddGhsKay();
        }

        private void FrmCgys_Shown(object sender, EventArgs e)
        {
            this.baseSearch1.AddConfig(2);
            this.kjm = this.baseSearch1._kjm;
        }
        private void baseSearch1_BtnScarchClick(object sender, EventArgs e)
        {
            this.Invalidate();
            this.savecgBtn.Enabled = false;
            this.kjm = this.baseSearch1._kjm;
            this.Cursor = Cursors.WaitCursor;
            string sql = this.baseSearch1.Sql;
            this.ysTime = this.baseSearch1.ystime;
            this.yeTime = this.baseSearch1.yetime;
            this.BookData = new BindingSource();
            this.dt = new DataTable();
            //DataTable d1 = new DataTable();
            using (DbOperHandler _open = new Common().Doh())
            {
                if (_open.dbType.ToString().Equals("ORACLE") || _open.odbType.ToString().Equals("ORACLE"))
                    flag = true;
                _open.Reset();
                _open.SqlCmd = sql;
                //Console.WriteLine(sql);
                this.dt = _open.GetDataTable();
                var dataRows = dt.AsEnumerable();
                foreach (var row in dataRows)
                {
                    var cellList = row.ItemArray.ToList();
                    row.ItemArray = cellList.Select(x => x.ToString().Trim()).ToArray();
                }
                this.dataGridBook.Columns.Clear();
                this.dataGridBook.AutoGenerateColumns = true;
                this.BookData.DataSource = dt;
                this.binNavBook.BindingSource = this.BookData;
                this.BookData.PositionChanged += new EventHandler(this.BookData_PositionChanged);
                this.dataGridBook.DataSource = this.BookData;
                this.dataGridBook.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);//宽度自适应
                this.dataGridBook.Columns.Remove(this.dataGridBook.Columns[this.dataGridBook.ColumnCount - 1]);
                if (this.BookData.Count == 0)
                {
                    MessageBox.Show("未检索到任何记录");
                    this.tdkBtn.Enabled = false;
                    this.copyMenuItem.Enabled = false;
                    //this.delBtn.Enabled = false;
                }
                else
                {
                    this.BookData_PositionChanged(sender, e);
                    this.copyMenuItem.Enabled = true;
                    this.tdkBtn.Enabled = true;
                    this.dlhTxt.Focus();
                    //this.delBtn.Enabled = true;
                }
            }
            this.Cursor = Cursors.Default;
        }
        private void getMpc()
        {
            DateTime currentTime = new System.DateTime();
            currentTime =DateTime.Now;
            string strYM = currentTime.ToString("yy");
            string strY = currentTime.ToString("yyyy");
            //Console.WriteLine("年月："+strYM+":"+strY);
            string pc = this.pcTxt.Text.Trim();
            using (DbOperHandler _open = new Common().Doh())
            {
                if (string.IsNullOrEmpty(pc))
                {
                    _open.Reset();
                    _open.ConditionExpress = "批次号 like '" + strY + "%'";
                    string mpc = _open.MaxValueS("采购库", "批次号");
                    if (string.IsNullOrEmpty(mpc))
                    {
                        this._mpc = strY + "001.0001";
                    }
                    else
                    {
                        try
                        {
                            int pcjs = Convert.ToInt32(mpc.Split('.')[1].Trim())+1;
                            this._mpc= mpc.Split('.')[0] + "." + pcjs.ToString().PadLeft(4,'0');
                        }
                        catch { }
                    }
                }
                else
                {
                    if(pc.StartsWith(strY) || pc.StartsWith(strYM))
                    {
                        if (pc.StartsWith(strYM))
                        {
                            string pct = strY + pc.Replace(strYM,"").PadLeft(3, '0');
                            _open.Reset();
                            _open.ConditionExpress = "批次号 like '" + pct + "%'";
                            string mpc = _open.MaxValueS("采购库", "批次号");
                            if (string.IsNullOrEmpty(mpc))
                            {
                                this._mpc = pct + ".0001";
                            }
                            else
                            {
                                try
                                {
                                    int pcjs = Convert.ToInt32(mpc.Split('.')[1].Trim()) + 1;
                                    this._mpc = mpc.Split('.')[0] + "." + pcjs.ToString().PadLeft(4, '0');
                                }
                                catch { }
                            }
                        }
                        if (pc.StartsWith(strY))
                        {
                            string pct = strY + pc.Replace(strY, "").PadLeft(3, '0');
                            _open.Reset();
                            _open.ConditionExpress = "批次号 like '" + pct + "%'";
                            string mpc = _open.MaxValueS("采购库", "批次号");
                            if (string.IsNullOrEmpty(mpc))
                            {
                                this._mpc = pct + ".0001";
                            }
                            else
                            {
                                try
                                {
                                    int pcjs = Convert.ToInt32(mpc.Split('.')[1].Trim()) + 1;
                                    this._mpc = mpc.Split('.')[0] + "." + pcjs.ToString().PadLeft(4, '0');
                                }
                                catch { }
                            }
                        }
                    }
                    else
                    {
                        string pct = strY+pc.PadLeft(3, '0');
                        _open.Reset();
                        _open.ConditionExpress = "批次号 like '" + pct + "%'";
                        string mpc = _open.MaxValueS("采购库", "批次号");
                        if (string.IsNullOrEmpty(mpc))
                        {
                            this._mpc = pct + ".0001";
                        }
                        else
                        {
                            try
                            {
                                int pcjs = Convert.ToInt32(mpc.Split('.')[1].Trim()) + 1;
                                this._mpc = mpc.Split('.')[0]+"." + pcjs.ToString().PadLeft(4, '0');
                            }
                            catch { }
                        }
                    }
                }
            }
            //Console.WriteLine("最大批次：" + this._mpc);
        }
        private void BookData_PositionChanged(object sender, EventArgs e)
        {
            DataRowView current = this.BookData.Current as DataRowView;
            if (current != null)
            {
                mainKay = current["主键码"].ToString().Trim();
                
                using (DbOperHandler _open = new Common().Doh())
                {
                    if (flag)
                    {
                        this.flag = true;
                        _open.Reset();
                        _open.ConditionExpress = " 主键码=" + mainKay;
                        marc = _open.GetField("MARC_DATA", "marc1").ToString();
                        if (string.IsNullOrEmpty(marc))
                            marc = _open.GetField("MARC_DATA", "marc2").ToString();
                        if (string.IsNullOrEmpty(marc))
                            marc = _open.GetField("MARC_DATA", "marc3").ToString();
                    }
                    else
                    {
                        _open.Reset();
                        _open.ConditionExpress = " 主键码=" + mainKay;
                        marc = _open.GetField("馆藏书目库", "marc").ToString();
                    }
                    _open.Reset();
                    _open.ConditionExpress = " 库键码=" + this.kjm;
                    int mlx = Convert.ToInt32(_open.GetField("书目数据库定义", "MARC类型").ToString().Trim());
                    if (!string.IsNullOrEmpty(marc))
                    {
                        this.marcGrid1.key = mainKay;
                        this.marcGrid1.kjm = this.kjm.ToString();
                        this.marcGrid1.MarcType = mlx;
                        try
                        {
                            MarcConvert convert = new MarcConvert();
                            convert.ISOData = marc;
                            if (marc.Split('\x001e')[0].Length < 25)
                            {
                                convert.MarcText = marc;
                                convert.SetISOStr();
                                convert.SetISOtoMarc();
                            }
                            else
                            {
                                convert.SetISOtoMarc();
                            }
                            this.marcGrid1.MarcText = convert.MarcText;
                            //this.mTxt = convert.MarcText;
                            this.marcGrid1.SetGridView();
                        }
                        catch { }
                    }
                    string sql = "select c.状态,c.订单号,c.预订日期,c.订购册数,c.订购单价,c.订购金额,c.币种,c.发行商键码,c.经费来源键码,f.发行商,j.经费名称,c.批次号,c.册数,c.单价,c.金额,c.验收日期,c.采购员,c.登录号,c.验收员,c.编目日期,c.编目员,c.典藏员,c.入藏日期,c.子键码 from 采购库 c left join 发行商库 f on c.发行商键码=f.键码 left join 采购经费库 j on j.键码=c.经费来源键码 where c.主键码=" + mainKay;
                    if (!string.IsNullOrEmpty(ysTime))
                        sql += " and  (c.验收日期 BETWEEN '" + ysTime + "' AND '" + yeTime + "')";
                    sql += " order by c.预订日期";
                    _open.Reset();
                    _open.SqlCmd = sql;
                    DataTable dcg = _open.GetDataTable();
                    for (int i = 0; i < dcg.Rows.Count; i++)
                    {
                        if (dcg.Rows[i]["状态"].ToString().Trim().Equals("C"))
                        {
                            if (string.IsNullOrEmpty(dcg.Rows[i]["登录号"].ToString().Trim()))
                                dcg.Rows[i]["状态"] = "采购";
                            else
                                dcg.Rows[i]["状态"] = "验收";
                        }
                        if (dcg.Rows[i]["状态"].ToString().Trim().Equals("G"))
                            dcg.Rows[i]["状态"] = "入藏";
                    }
                    this.CfData = new BindingSource();
                    //this.dataGridCg.AutoGenerateColumns = false;
                    this.CfData.DataSource = dcg;
                    dataGridCg.DataSource = this.CfData;
                    this.CfData.PositionChanged += new EventHandler(this.CfData_PositionChanged);
                    this.dataGridCg.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);//宽度自适应
                    for (int i = 0; i < this.dataGridCg.Columns.Count; i++)
                    {
                        this.dataGridCg.Columns[i].ReadOnly = true;
                    }
                    if (this.CfData.Count > 0)
                    {
                        this.dataGridCg.Columns[this.dataGridCg.Columns.Count - 1].Visible = false;
                        this.dataGridCg.CurrentCell = this.dataGridCg.Rows[this.dataGridCg.Rows.Count - 1].Cells[0];
                        //模拟点击事件（点击选中行）
                        this.dataGridCg_CellClick(dataGridCg, new DataGridViewCellEventArgs(dataGridCg.SelectedCells[0].ColumnIndex, dataGridCg.SelectedCells[0].RowIndex));
                        this.CfData_PositionChanged(sender, e);
                    }
                }
            }
        }
        private void CfData_PositionChanged(object sender, EventArgs e)
        {
            DataRowView current = this.CfData.Current as DataRowView;
            if (current.Row != null)
            {
                string type = current["状态"].ToString().Trim();
                string dlh = current["登录号"].ToString().Trim();
                string yddj = current["订购单价"].ToString().Trim();
                string ydcs = current["订购册数"].ToString().Trim();
                string ydje = current["订购金额"].ToString().Trim();
                string dj = current["单价"].ToString().Trim();
                string cs = current["册数"].ToString().Trim();
                string je = current["金额"].ToString().Trim();
                string ydrq = current["预订日期"].ToString().Trim();
                this.ghsjm = Convert.ToInt32(current["发行商键码"].ToString().Trim());
                this.jfjm = Convert.ToInt32(current["经费来源键码"].ToString().Trim());
                int gindex = GhsjmList.FindIndex(item => item.Equals(this.ghsjm));
                this.fxsKay.SelectedIndex = gindex;
                int jindex = JfjmList.FindIndex(item => item.Equals(this.jfjm));
                this.jfKay.SelectedIndex = jindex;
                this.dgrqTxt.Text = ydrq.Trim();
                this.dgrqTxt.ReadOnly = true;
                this.ddhTxt.Text = current["订单号"].ToString().Trim();
                this.ddhTxt.ReadOnly = true;
                this.dlhTxt.Text = dlh.Trim();
                this.djTxt.Text = yddj.Trim();
                this.shyTxt.Text = yddj.Trim();
                if (!string.IsNullOrEmpty(dj) && Convert.ToDouble(dj) > 0)
                {
                    this.djTxt.Text = dj.Trim();
                    this.shyTxt.Text = dj.Trim();
                }
                this.csTxt.Text = ydcs.Trim();
                if (!string.IsNullOrEmpty(cs) && Convert.ToInt32(cs) > 0)
                    this.csTxt.Text = cs.Trim();
                this.jeTxt.Text = ydje.Trim();
                
                if (!string.IsNullOrEmpty(je) && Convert.ToDouble(je) > 0)
                {
                    this.jeTxt.Text = je.Trim();
                }
                this.qxysBtn.Enabled = false;
                if (!type.Equals("采购"))
                {
                    this.dlhTxt.ReadOnly = true;
                    this.djTxt.ReadOnly = true;
                    this.csTxt.ReadOnly = true;
                    if (type.Equals("验收"))
                    {
                        this.qxysBtn.Enabled = true;
                    }
                }
                else
                {
                    this.qxysBtn.Enabled = false;
                    this.dlhTxt.ReadOnly = false;
                    this.djTxt.ReadOnly = false;
                    this.csTxt.ReadOnly = false;
                }
            }
        }

        private void dataGridCg_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1)
                if (e != null)
                    this.dataGridCg.Rows[e.RowIndex].Selected = true;
        }

        private void jfKay_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = this.jfKay.SelectedIndex;
            this.jfjm =this.JfjmList[index];
        }

        private void fxsKay_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = this.fxsKay.SelectedIndex;
            this.ghsjm =this.GhsjmList[index];
        }

        private void dlh_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                string dlh = "", cs = "";
                this.getMpc();
                this.dlKeyPress(out dlh, out cs);
                DataRowView current = this.CfData.Current as DataRowView;
                if (current != null && !string.IsNullOrEmpty(dlh))
                {
                    string zjm = current["子键码"].ToString().Trim();
                    using (DbOperHandler _open = new Common().Doh())
                    {
                        _open.Reset();
                        _open.ConditionExpress = "馆键码=" + this.gjm;
                        string gdm = _open.GetField("系统单位定义", "单位代码").ToString().Trim();
                        _open.Reset();
                        _open.ConditionExpress = "主键码=" + mainKay + " and 子键码=" + zjm;
                        object[,] value = new object[9, 2] {
                            {"册数",cs},
                            {"单价",this.djTxt.Text.Trim()},
                            {"登录号",dlh},
                            {"金额",this.jeTxt.Text.Trim()},
                            {"实洋",this.shyTxt.Text.Trim()},
                            {"实洋金额",Convert.ToDouble(this.shyTxt.Text.Trim())*Convert.ToInt32(cs)},
                            {"验收日期",DateTime.Now},
                            {"批次号",this._mpc},
                            {"验收员",this.uid}
                        };
                        _open.AddFieldItems(value);
                        _open.Update("采购库");
                        this.BookData_PositionChanged(sender, e);
                        _open.Reset();
                        _open.SqlCmd = "select 登录号,册数 from 采购库 where 主键码=" + mainKay;
                        DataTable cdl = _open.GetDataTable();
                        string dls = string.Empty; int gcs = 0;
                        for (int i = 0; i < cdl.Rows.Count; i++)
                        {
                            if (!string.IsNullOrEmpty(cdl.Rows[i]["登录号"].ToString()))
                                dls += cdl.Rows[i]["登录号"] + ";";
                            if (!string.IsNullOrEmpty(cdl.Rows[i]["册数"].ToString()))
                                gcs += Convert.ToInt32(cdl.Rows[i]["册数"]);
                        }
                        if (!string.IsNullOrEmpty(dls))
                        {
                            dls = dls.Substring(0, dls.Length - 1);
                            //Console.WriteLine(dls);
                            MarcConvert convert = new MarcConvert();
                            convert.MarcText = this.marc;
                            convert.ReplaceSubfield("905", "a", 1, gdm);
                            convert.ReplaceSubfield("905", "b", 1, dls);
                            convert.ReplaceSubfield("905", "f", 1, gcs.ToString());
                            marc = convert.MarcText;
                            this.marcGrid1.zdmenu(convert);
                            this.marcGrid1.MarcText = convert.MarcText;
                            this.marcGrid1.SetGridView();
                            _open.Reset();
                            _open.ConditionExpress = "主键码=" + mainKay;
                            if (flag)
                            {
                                try
                                {
                                    convert.SetISOStr();
                                    _open.AddFieldItem("marc1", convert.ISOData);
                                    _open.Update("MARC_DATA");
                                }
                                catch { }
                            }
                            else
                            {
                                _open.AddFieldItem("marc", convert.MarcText);
                                _open.Update("馆藏书目库");
                            }
                            this.marcGrid1.savemarc();
                            List<string> list = StringUtil.getDlhs(dls);
                            foreach(string sdlh in list)
                            {
                                _open.Reset();
                                _open.ConditionExpress = "登录号 ='" + sdlh + "'";
                                if (!_open.Exist("馆藏典藏库"))
                                {
                                    object[,] value1 = new object[11, 2] {
                                        {"主键码",mainKay},
                                        {"子键码", zjm},
                                        {"库键码",this.kjm},
                                        {"登录号",sdlh},
                                        {"馆键码",this.gjm},
                                        {"条形码",sdlh},
                                        {"馆藏地址","A"},
                                        {"虚拟库室",1},
                                        {"状态","C"},
                                        {"操作员",this.uid},
                                        {"处理日期",DateTime.Now}
                                    };
                                    _open.AddFieldItems(value1);
                                    _open.Insert("馆藏典藏库");
                                }
                            }
                            _open.Reset();
                            _open.ConditionExpress = "主键码=" + this.mainKay;
                            string ssh = _open.GetField("馆藏书目库", "索书号").ToString().Trim();
                            DataGridViewRow row = this.dataGridBook.SelectedRows[0];
                            row.Cells["索书号"].Value=ssh;
                            this.dataGridBook.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);//宽度自适应
                            this.baseSearch1.sTxt.Text = "";
                            this.baseSearch1.sTxt.Focus();
                        }
                    }
                }
            }
        }
        private void dlKeyPress(out string dlh, out string dcs)
        {
            string xdlh = StringUtil.ToDBC(this.dlhTxt.Text.Trim());
            if (!xdlh.Contains("-") && !xdlh.Contains(";-"))
            {
                string y1 = "0";
                string cst = this.csTxt.Text.Trim();
                var reg = new Regex("[0-9]+", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                var mc = reg.Matches(xdlh);
                foreach (Match m in mc)
                {
                    //将会返回123、456、789
                    var val = m.Groups[0].Value;
                    y1 = val;
                }
                try
                {
                    int yds = Convert.ToInt32(cst);
                    if (yds > 1)
                    {
                        long cs = long.Parse(y1) + yds - 1;
                        string css = cs.ToString(); string dlhz = string.Empty;
                        for (int i = 0; i < y1.Length; i++)
                        {
                            if (!y1[i].Equals(css[i]))
                            {
                                dlhz = css.Substring(i);
                                break;
                            }
                        }
                        xdlh += "-" + dlhz;
                    }
                }
                catch { }
                this.dlhTxt.Text = xdlh;
            }
            List<string> list = StringUtil.getDlhs(xdlh);
            bool f = false; string cfdlh = "";
            using (DbOperHandler _open = new Common().Doh())
            {
                foreach (string str in list)
                {
                    _open.Reset();
                    _open.ConditionExpress = "登录号='" + str + "' or 条形码='" + str + "'";
                    f = _open.Exist("馆藏典藏库");
                    if (f)
                    {
                        cfdlh = str;
                        break;
                    }
                }
                if (!f)
                {
                    _open.Reset();
                    _open.ConditionExpress = "登录号='" + xdlh + "'";
                    f = _open.Exist("采购库");
                    if (f)
                        cfdlh = xdlh;
                }
                if (!f)
                {
                    _open.Reset();
                    _open.SqlCmd = "select 登录号 from 采购库 where 登录号 is not null AND 状态='C'";
                    DataTable dr = _open.GetDataTable();
                    foreach (DataRow drow in dr.Rows)
                    {
                        List<string> list1 = StringUtil.getDlhs(drow["登录号"].ToString());
                        foreach (string str in list)
                        {
                            foreach (string str1 in list1)
                            {
                                if (str1.Equals(str))
                                {
                                    f = true;
                                    cfdlh = str1;
                                    break;
                                }
                            }
                            if (f)
                                break;
                        }
                    }
                }
            }
            if (f)
            {
                dcs = ""; dlh = "";
                ShowMessageBox.ShowMessageBoxTimeout("【" + cfdlh + "】登录号重复，请重试...", "警告", MessageBoxButtons.OK, 3000);
            }
            else
            {
                dcs = list.Count.ToString();
                this.csTxt.Text = dcs;
                try
                {
                    this.jeTxt.Text = (Convert.ToInt32(dcs) * Convert.ToInt32(this.djTxt.Text.Trim())).ToString();
                    this.shyTxt.Text = this.djTxt.Text.Trim();
                }
                catch { }
                dlh = xdlh;
            }
        }

        private void qxysBtn_Click(object sender, EventArgs e)
        {
            DataRowView current = this.CfData.Current as DataRowView;
            if (current.Row != null)
            {
                string zjm = current["子键码"].ToString().Trim();
                string dlh = current["登录号"].ToString().Trim();
                string cs = current["册数"].ToString().Trim();
                using (DbOperHandler _open = new Common().Doh())
                {
                    _open.Reset();
                    _open.SqlCmd = "update 采购库 set 册数=null,单价=null,登录号=null,金额=null,验收日期=null,验收员=null,批次号=null where 主键码=" + mainKay + " and 子键码=" + zjm;
                    _open.ExecuteSqlNonQuery();
                    MarcConvert convert = new MarcConvert();
                    convert.MarcText = this.marc;
                    string gcd= convert.GetASubField("905", "d", 1);
                    string gce = convert.GetASubField("905", "e", 1);
                    if (!string.IsNullOrEmpty(gce))
                        gcd += "/" + gce;
                    string xdlh = convert.GetASubField("905", "b", 1);
                    string xcs = convert.GetASubField("905", "f", 1);
                    xdlh = xdlh.Replace(dlh + ";", "").Replace(dlh, "");
                    if (string.IsNullOrEmpty(xdlh))
                        convert.DeleteField("905", "b", 1);
                    else
                        convert.ReplaceSubfield("905", "b", 1, xdlh);
                    if (!string.IsNullOrEmpty(xcs))
                    {
                        int xs = Convert.ToInt32(xcs) - Convert.ToInt32(cs);
                        if (xs > 0)
                            convert.ReplaceSubfield("905", "f", 1, xs.ToString());
                        else
                            convert.DeleteField("905", "f", 1);
                    }
                    this.marc = convert.MarcText;
                    this.marcGrid1.MarcText = this.marc;
                    this.marcGrid1.SetGridView();
                    if (MessageBox.Show("MARC数据已修改，是否更新？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                    {
                        _open.Reset();
                        _open.ConditionExpress = "主键码=" + mainKay;
                        if (flag)
                        {
                            try
                            {
                                convert.SetISOStr();
                                _open.AddFieldItem("marc1", convert.ISOData);
                                _open.Update("MARC_DATA");
                            }
                            catch { }
                        }
                        else
                        {
                            _open.AddFieldItem("marc", convert.MarcText);
                            _open.Update("馆藏书目库");
                        }
                    }
                    List<string> list = StringUtil.getDlhs(dlh);
                    foreach (string sdlh in list)
                    {
                        _open.Reset();
                        _open.ConditionExpress = "登录号 ='" + sdlh + "'";
                        if (_open.Exist("馆藏典藏库"))
                        {
                           _open.Delete("馆藏典藏库");
                        }
                    }
                    _open.Reset();
                    _open.SqlCmd = " update 馆藏书目库 set 索书号=null,分类号=null where 主键码=" + this.mainKay;
                    _open.ExecuteSqlNonQuery();
                    DataGridViewRow row = this.dataGridBook.SelectedRows[0];
                    row.Cells["索书号"].Value = null;
                    this.dataGridBook.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);//宽度自适应
                    _open.Reset();
                    _open.ConditionExpress = "索书号='" + gcd + "' and 主键码=" + this.mainKay;
                    _open.Delete("检索索书号库");
                    this.BookData_PositionChanged(sender, e);
                }
            }
        }

        private void dataGridCg_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Right)
                {
                    if (e.RowIndex >= 0)
                    {
                        dataGridCg.ClearSelection();
                        dataGridCg.Rows[e.RowIndex].Selected = true;
                        dataGridCg.CurrentCell = dataGridCg.Rows[e.RowIndex].Cells[e.ColumnIndex];
                        dcgMenu.Show(MousePosition.X, MousePosition.Y);
                        string type = dataGridCg.Rows[e.RowIndex].Cells["状态"].Value.ToString().Trim();
                        if (type.Equals("采购"))
                            this.dcgMenuItem.Enabled = true;
                        else
                            this.dcgMenuItem.Enabled = false;
                        if (type.Equals("验收"))
                            this.rgcMenuItem.Enabled = true;
                        else
                            this.rgcMenuItem.Enabled = false;
                        if (type.Equals("入藏"))
                            this.tgcMenuItem.Enabled = true;
                        else
                            this.tgcMenuItem.Enabled = false;
                    }
                }
            }
            catch (Exception)
            { }
        }

        private void dcgMenuItem_Click(object sender, EventArgs e)
        {
            using (DbOperHandler _open = new Common().Doh())
            {
                _open.Reset();
                _open.ConditionExpress = "主键码=" + mainKay;
                int count = _open.Count("采购库");
                if (count == 1)
                {
                    if (MessageBox.Show("确认要当前采购记录吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                    {
                        _open.Reset();
                        _open.ConditionExpress = "主键码=" + mainKay;
                        _open.Delete("馆藏书目库");
                        this.baseSearch1_BtnScarchClick(sender, e);
                    }
                }
                else
                {
                    DataRowView current = this.CfData.Current as DataRowView;
                    if (current.Row != null)
                    {
                        string zjm = current["子键码"].ToString().Trim();
                        if (MessageBox.Show("确认要当前采购记录吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                        {
                            _open.Reset();
                            _open.ConditionExpress = "主键码=" + mainKay + " and 子键码=" + zjm;
                            _open.Delete("采购库");
                            this.BookData_PositionChanged(sender, e);
                        }
                    }
                }

            }
        }

        private void rgcMenuItem_Click(object sender, EventArgs e)
        {
            DataRowView current = this.CfData.Current as DataRowView;
            if (current.Row != null)
            {
                string zjm = current["子键码"].ToString().Trim();
                string dlh = current["登录号"].ToString().Trim();
                if (MessageBox.Show("确认要入藏当前采购记录吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                {
                    string strError;
                    bool df;
                    this.Dc(dlh, zjm, out strError, out df);
                    if (df)
                    {
                        ShowMessageBox.ShowMessageBoxTimeout("入藏操作成功", "提示", MessageBoxButtons.OK, 2000);
                        this.BookData_PositionChanged(sender, e);
                    }
                    else
                        ShowMessageBox.ShowMessageBoxTimeout(strError, "警告", MessageBoxButtons.OK, 2000);
                }
            }
        }
        private void Dc(string dlh, string zjm, out string StrError, out bool flag)
        {
            try
            {
                FrmCgysXk f = new FrmCgysXk();
                f.AddConfig(this.kjm);
                if (f.ShowDialog() == DialogResult.OK)
                {
                    int xnk = f.xnkId;
                    string gcd = f.gcd;
                    using (DbOperHandler _open = new Common().Doh())
                    {
                        List<string> list = StringUtil.getDlhs(dlh);
                        _open.Reset();
                        _open.ConditionExpress = "主键码=" + mainKay;
                        string ssh = _open.GetField("检索索书号库", "索书号").ToString().Trim();
                        foreach (string xdlh in list)
                        {
                            object[,] value = new object[6, 2] {
                                        {"馆藏地址",gcd},
                                        {"虚拟库室",xnk},
                                        {"处理日期",DateTime.Now},
                                        {"索书号",ssh},
                                        {"操作员",this.uid},
                                        {"状态","G"}
                                        };
                            _open.Reset();
                            _open.ConditionExpress = "主键码=" + mainKay + " and 子键码=" + zjm+" and 登录号='"+xdlh+"'";
                            _open.AddFieldItems(value);
                            _open.Update("馆藏典藏库");
                        }
                        _open.Reset();
                        _open.ConditionExpress = "主键码=" + mainKay + " and 子键码=" + zjm;
                        _open.AddFieldItem("典藏员", this.uid);
                        _open.AddFieldItem("典藏分配日期", DateTime.Now);
                        _open.AddFieldItem("入藏日期", DateTime.Now);
                        _open.AddFieldItem("状态", "G");
                        _open.Update("采购库");
                    }
                    StrError = "";
                    flag = true;
                }
                else
                {
                    StrError = "入藏失败,未选择收藏库室！";
                    flag = false;
                }

            }
            catch (Exception ex)
            {
                StrError = ex.Message;
                flag = false;
            }
        }

        private void dgcMenuItem_Click(object sender, EventArgs e)
        {
            DataRowView current = this.CfData.Current as DataRowView;
            if (current.Row != null)
            {
                string zjm = current["子键码"].ToString().Trim();
                string dlh = current["登录号"].ToString().Trim();
                if (MessageBox.Show("确认要入藏当前采购记录吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                {
                    string strError;
                    bool df;
                    this.Dc(dlh, zjm, out strError, out df);
                    if (df)
                    {
                        ShowMessageBox.ShowMessageBoxTimeout("入藏操作成功", "提示", MessageBoxButtons.OK, 2000);
                        this.BookData_PositionChanged(sender, e);
                    }
                    else
                        ShowMessageBox.ShowMessageBoxTimeout(strError, "警告", MessageBoxButtons.OK, 2000);
                }
            }
        }
        /// <summary>
        /// 全部验收记录入馆藏
        /// </summary>
        private void qgcMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认要检索到已验收记录导入馆藏吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
                FrmCgysSh f = new FrmCgysSh();
                f.AddConfig(this.kjm);
                if (f.ShowDialog() == DialogResult.OK)
                {
                    int m = 0, n = 0;
                    using (DbOperHandler _open = new Common().Doh())
                    {
                        FrmWait wait = new FrmWait();
                        wait.Show();
                        for (int i = 0; i < this.dataGridBook.Rows.Count; i++)
                        {
                            List<string[]> list = f.list;
                            _open.Reset();
                            _open.ConditionExpress = "主键码=" + mainKay;
                            string flh = _open.GetField("馆藏书目库", "分类号").ToString().Trim();
                            int xnk = 1; string gcd = "A";
                            foreach (string[] arry in list)
                            {
                                string[] fls = arry[0].Split('-');

                                if (string.Compare(flh, fls[0], true) >= 0 && string.Compare(flh, fls[1], true) <= 0)
                                {
                                    xnk = Convert.ToInt32(arry[1]);
                                    gcd = arry[2].Trim();
                                    break;
                                }
                            }
                            this.dataGridBook.CurrentCell = this.dataGridBook.Rows[i].Cells[0];
                            //模拟点击事件（点击选中行）
                            this.dataGridBook_CellClick(dataGridBook, new DataGridViewCellEventArgs(dataGridBook.SelectedCells[0].ColumnIndex, dataGridBook.SelectedCells[0].RowIndex));
                            string sql = "select 登录号,子键码 from 采购库 where 主键码=" + mainKay + " and 状态='C' and 登录号 is not null ";
                            if (!string.IsNullOrEmpty(ysTime))
                                sql += " and  (验收日期 BETWEEN '" + ysTime + "' AND '" + yeTime + "')";
                            sql += " order by 预订日期";
                            _open.Reset();
                            _open.SqlCmd = sql;
                            DataTable dcg = _open.GetDataTable();
                            for (int j = 0; j < dcg.Rows.Count; j++)
                            {
                                string zjm = dcg.Rows[j]["子键码"].ToString().Trim();
                                string dlh = dcg.Rows[j]["登录号"].ToString().Trim();
                                if (!string.IsNullOrEmpty(dlh))
                                {
                                    string strError; bool df;
                                    this.AllDc(dlh, zjm, xnk, gcd, out strError, out df);
                                    if (df)
                                    {
                                        m++;
                                    }
                                    else
                                        n++;
                                }
                                else
                                    n++;
                            }
                            wait.label4.Text = (i + 1).ToString();
                            Application.DoEvents();
                        }
                        wait.Close();
                    }
                    ShowMessageBox.ShowMessageBoxTimeout("入藏操作完成，成功[ " + m + " ]条;失败[" + n + "]条", "提示", MessageBoxButtons.OK, 2000);

                }
            }
        }
        private void AllDc(string dlh, string zjm, int xnk, string gcd, out string StrError, out bool flag)
        {
            try
            {
                using (DbOperHandler _open = new Common().Doh())
                {
                    List<string> list = StringUtil.getDlhs(dlh);
                    _open.Reset();
                    _open.ConditionExpress = "主键码=" + mainKay;
                    string ssh = _open.GetField("检索索书号库", "索书号").ToString().Trim();
                    foreach (string xdlh in list)
                    {
                        List<int> zjmList = new List<int>();
                        _open.Reset();
                        _open.SqlCmd = " select 子键码 from 馆藏典藏库 order by 子键码";
                        DataTable dcg = _open.GetDataTable();
                        if (dcg.Rows.Count > 0)
                        {
                            for (int i = 0; i < dcg.Rows.Count; i++)
                            {
                                //Console.WriteLine(dcg.Rows[i]["子键码"].ToString());
                                zjmList.Add(Convert.ToInt32(dcg.Rows[i]["子键码"].ToString()));
                            }
                        }
                        int czjm = StringUtil.GetNextNumber(zjmList);
                        object[,] value = new object[12, 2] {
                                        {"主键码",this.mainKay},
                                        {"子键码",czjm},
                                        {"登录号",xdlh},
                                        {"条形码",xdlh},
                                        {"馆键码",1},
                                        {"馆藏地址",gcd},
                                        {"虚拟库室",xnk},
                                        {"处理日期",DateTime.Now},
                                        {"索书号",ssh},
                                        {"操作员",this.uid},
                                        {"库键码",this.kjm},
                                        {"状态","G"}
                                        };
                        _open.Reset();
                        _open.AddFieldItems(value);
                        _open.Insert("馆藏典藏库");
                    }
                    _open.Reset();
                    _open.ConditionExpress = "主键码=" + mainKay + " and 子键码=" + zjm;
                    _open.AddFieldItem("典藏员", this.uid);
                    _open.AddFieldItem("典藏分配日期", DateTime.Now);
                    _open.AddFieldItem("入藏日期", DateTime.Now);
                    _open.AddFieldItem("状态", "G");
                    _open.Update("采购库");
                }
                StrError = "";
                flag = true;
            }
            catch (Exception ex)
            {
                StrError = ex.Message;
                flag = false;
            }
        }
        private void dataGridBook_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1)
                if (e != null)
                    this.dataGridBook.Rows[e.RowIndex].Selected = true;
        }

        private void cs_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                try
                {
                    double dj = Convert.ToDouble(this.djTxt.Text.Trim());
                    int cs = Convert.ToInt32(this.csTxt.Text.Trim());
                    this.jeTxt.Text = (dj * cs).ToString();
                    this.shyTxt.Text = (dj).ToString();
                }
                catch { }
            }
        }

        private void dj_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                try
                {
                    double dj = Convert.ToDouble(this.djTxt.Text.Trim());
                    int cs = Convert.ToInt32(this.csTxt.Text.Trim());
                    this.jeTxt.Text = (dj * cs).ToString();
                    this.shyTxt.Text = (dj).ToString();
                }
                catch { }
            }
        }

        private void newMenuItem_Click(object sender, EventArgs e)
        {
            this.kjm = this.baseSearch1._kjm;
            MarcConvert convert = new MarcConvert();
            convert.GetCnNmarc();
            this.marcGrid1.MarcText=convert.MarcText;
            this.marcGrid1.kjm = this.kjm.ToString();
            using (DbOperHandler _open = new Common().Doh())
            {
                _open.Reset();
                _open.ConditionExpress = " 库键码=" + this.kjm;
                int mlx = Convert.ToInt32(_open.GetField("书目数据库定义", "MARC类型").ToString().Trim());
                this.marcGrid1.MarcType = mlx;
            }
            this.marcGrid1.Uid = this.uid;
            this.marcGrid1.SetGridView();
            string ddh = this.ddhTxt.Text.Trim();
            if (string.IsNullOrEmpty(ddh))
                this.ddhTxt.Text = DateTime.Now.ToString("yyyyMMdd");
            string dgrq = this.dgrqTxt.Text.Trim();
            if (string.IsNullOrEmpty(dgrq))
                this.dgrqTxt.Text = DateTime.Now.ToString();
            this.savecgBtn.Enabled = true;
        }

        private void copyMenuItem_Click(object sender, EventArgs e)
        {
            DataRowView current = this.BookData.Current as DataRowView;
            if (current != null)
            {
                mainKay = current["主键码"].ToString().Trim();

                using (DbOperHandler _open = new Common().Doh())
                {
                    if (flag)
                    {
                        this.flag = true;
                        _open.Reset();
                        _open.ConditionExpress = " 主键码=" + mainKay;
                        marc = _open.GetField("MARC_DATA", "marc1").ToString();
                        if (string.IsNullOrEmpty(marc))
                            marc = _open.GetField("MARC_DATA", "marc2").ToString();
                        if (string.IsNullOrEmpty(marc))
                            marc = _open.GetField("MARC_DATA", "marc3").ToString();
                    }
                    else
                    {
                        _open.Reset();
                        _open.ConditionExpress = " 主键码=" + mainKay;
                        marc = _open.GetField("馆藏书目库", "marc").ToString();
                    }
                    _open.Reset();
                    _open.ConditionExpress = " 库键码=" + this.kjm;
                    int mlx = Convert.ToInt32(_open.GetField("书目数据库定义", "MARC类型").ToString().Trim());
                    if (!string.IsNullOrEmpty(marc))
                    {
                        this.marcGrid1.kjm = this.kjm.ToString();
                        this.marcGrid1.MarcType = mlx;
                        try
                        {
                            MarcConvert convert = new MarcConvert();
                            convert.ISOData = marc;
                            if (marc.Split('\x001e')[0].Length < 25)
                            {
                                convert.MarcText = marc;
                                convert.SetISOStr();
                                convert.SetISOtoMarc();
                            }
                            else
                            {
                                convert.SetISOtoMarc();
                            }
                            convert.DeleteField("905", "b", 1);
                            convert.DeleteField("905", "f", 1);
                            this.marcGrid1.MarcText = convert.MarcText;
                            this.marcGrid1.key = "";
                            this.marcGrid1.kjm = this.kjm.ToString();
                            this.marcGrid1.Uid = this.uid;
                            this.marcGrid1.SetGridView();
                        }
                        catch { }
                    }
                }
            }
            DataRowView cfcurrent = this.CfData.Current as DataRowView;
            this.csTxt.ReadOnly = false;
            this.djTxt.ReadOnly = false;
            this.dlhTxt.ReadOnly = false;
            this.savecgBtn.Enabled = true;
        }

        private void savecgBtn_Click(object sender, EventArgs e)
        {
            this.marcGrid1.saveNmarc();
            this.mainKay = this.marcGrid1.key;
            if (string.IsNullOrEmpty(this.mainKay))
            {
                return;
            }
            else
            {
                using (DbOperHandler _open = new Common().Doh())
                {
                    _open.Reset();
                    _open.AddFieldItem("主键码", this.mainKay);
                    _open.AddFieldItem("发行商键码", this.ghsjm);
                    _open.AddFieldItem("经费来源键码", this.jfjm);
                    _open.AddFieldItem("状态", "C");
                    _open.AddFieldItem("订单号", this.ddhTxt.Text.Trim());
                    _open.AddFieldItem("馆键码", this.gjm);
                    _open.AddFieldItem("库键码", this.kjm);
                    _open.AddFieldItem("征订书目键码", 0);
                    _open.AddFieldItem("订购套数", 0);
                    _open.AddFieldItem("订购册数", this.csTxt.Text.Trim());
                    _open.AddFieldItem("订购单价", this.djTxt.Text.Trim());
                    _open.AddFieldItem("订购金额", this.jeTxt.Text.Trim());
                    _open.AddFieldItem("采购员", this.uid);
                    _open.Insert("采购库");
                    _open.Reset();
                    _open.ConditionExpress = "主键码=" + this.mainKay;
                    string isbn = _open.GetField("馆藏书目库", "标准编码").ToString().Trim();
                    this.baseSearch1.sTxt.Text = isbn;
                    this.baseSearch1_BtnScarchClick(sender, e);
                }
            }
        }

        private void exitBtn_Click(object sender, EventArgs e)
        {
            base.Close();
        }
    }
}
